# -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QLabel, QLineEdit, QPushButton, 
                            QTableWidget, QTableWidgetItem, QHeaderView)
from tqsdk import TqApi, TqAuth, TqAccount

class StopStrategyWindow(QMainWindow):
    update_signal = pyqtSignal(str)
    connection_signal = pyqtSignal(str, bool)

    def __init__(self):
        super().__init__()
        self.api = None
        self.tq_account = None
        self.strategy_running = False
        self.init_ui()
        self.setup_connections()
        self.setWindowTitle("智能止盈止损系统")
        self.resize(800, 600)

    def init_ui(self):
        """核心界面初始化"""
        main_widget = QWidget()
        main_layout = QVBoxLayout(main_widget)

        # 账户连接组件
        connect_layout = QHBoxLayout()
        self.connect_btn = QPushButton("连接天勤账户")
        self.capital_label = QLabel("可用资金: --")
        connect_layout.addWidget(self.connect_btn)
        connect_layout.addStretch()
        connect_layout.addWidget(self.capital_label)

        # 策略控制组件
        strategy_control = QHBoxLayout()
        self.strategy_switch = QPushButton("启动止盈止损策略")
        self.strategy_switch.setCheckable(True)
        self.qty_input = QLineEdit("1")
        self.qty_input.setValidator(QIntValidator(1, 1000))
        strategy_control.addWidget(QLabel("单次操作量:"))
        strategy_control.addWidget(self.qty_input)
        strategy_control.addWidget(self.strategy_switch)

        # 监控表格
        self.monitor_table = QTableWidget(0, 5)
        self.monitor_table.setHorizontalHeaderLabels(["合约", "方向", "持仓量", "最新价", "浮动盈亏"])
        self.monitor_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 布局组装
        main_layout.addLayout(connect_layout)
        main_layout.addLayout(strategy_control)
        main_layout.addWidget(self.monitor_table)
        self.setCentralWidget(main_widget)

    def setup_connections(self):
        """信号连接"""
        self.connect_btn.clicked.connect(self.toggle_connection)
        self.strategy_switch.clicked.connect(self.toggle_strategy)
        self.update_signal.connect(self.capital_label.setText)
        self.connection_signal.connect(self.handle_connection)

    def toggle_connection(self):
        """账户连接/断开"""
        if "断开" in self.connect_btn.text():
            self.disconnect_account()
        else:
            self.connect_account()

    def connect_account(self):
        """连接天勤账户"""
        self.connect_btn.setEnabled(False)
        self.connect_btn.setText("连接中...")
        
        import threading
        threading.Thread(target=self._connect_thread, daemon=True).start()

    def _connect_thread(self):
        """连接线程"""
        try:
            self.tq_account = TqAccount("H徽商期货", "155831", "alibaba999")
            self.api = TqApi(self.tq_account, auth=TqAuth("szlwy68", "alibaba999"))
            account = self.api.get_account()
            
            self.update_signal.emit(f"可用资金: {account.available:.2f}")
            self.connection_signal.emit("已连接 (点击断开)", True)
            
        except Exception as e:
            self.connection_signal.emit(f"连接失败: {str(e)}", False)

    def handle_connection(self, text, success):
        """更新连接状态"""
        self.connect_btn.setText(text)
        self.connect_btn.setEnabled(True)
        if success:
            self.strategy_switch.setEnabled(True)
        else:
            self.strategy_switch.setEnabled(False)

    def toggle_strategy(self):
        """策略开关"""
        if self.strategy_switch.isChecked():
            self.start_strategy()
        else:
            self.stop_strategy()

    def start_strategy(self):
        """启动策略核心逻辑"""
        self.strategy_running = True
        self.strategy_switch.setText("停止策略")
        self.qty_input.setEnabled(False)
        
        import threading
        threading.Thread(target=self.run_strategy, daemon=True).start()

    def run_strategy(self):
        """策略执行逻辑"""
        while self.strategy_running and self.api:
            try:
                quotes = self.api.get_quote_list()
                
                for symbol in [q.symbol for q in quotes]:
                    position = self.api.get_position(symbol)
                    klines = self.api.get_kline_serial(symbol, 900, 25)
                    
                    if len(klines) >= 25:
                        ma_value = sum(klines.close[-25:]) / 25
                        last_close = klines.close[-1]
                        
                        # 多单止损逻辑
                        if position.pos_long > 0 and last_close < ma_value:
                            self.api.insert_order(symbol, "SELL", "CLOSE", position.pos_long)
                        
                        # 空单止损逻辑
                        if position.pos_short > 0 and last_close > ma_value:
                            self.api.insert_order(symbol, "BUY", "CLOSE", position.pos_short)
                            
                self.api.wait_update()
            except Exception as e:
                print(f"策略执行异常: {str(e)}")
                break

    def stop_strategy(self):
        """停止策略"""
        self.strategy_running = False
        self.strategy_switch.setText("启动策略")
        self.qty_input.setEnabled(True)

    def disconnect_account(self):
        """断开连接"""
        if self.api:
            self.api.close()
            self.api = None
        self.capital_label.setText("可用资金: --")
        self.connect_btn.setText("连接天勤账户")
        self.strategy_switch.setChecked(False)
        self.stop_strategy()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = StopStrategyWindow()
    window.show()
    sys.exit(app.exec_())